
import axios from 'axios'
import { Toast, Dialog } from 'vant'
import router from '../router'
import storage from '@/utils/storage'
import qs from 'qs'
import { BASE_URL, openWebUrl } from "./config";
import cookie from '@/utils/cookie'
// let timer: any = null
const userInfo = cookie.readCookie('userInfo') ? JSON.parse(cookie.readCookie('userInfo')) : '';
axios.defaults.baseURL = BASE_URL
axios.defaults.withCredentials = true
axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest'
axios.defaults.headers['Authorization'] = userInfo ? userInfo.userCode : ''
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
//  ctx.headers = {
//         Accept: 'application/json',
//         Authorization: JSON.parse(localStorage.getItem('userCode')) || '',
//         ...ctx.headers,
//       }
axios.interceptors.request.use((config: any) => {
  if (config.method === 'post') {
    config.data = qs.stringify(config.data, {
      allowDots: true,
    })
  }
  // config.timer = setTimeout(() => {
  //   Toast.loading({
  //     message: '加载中...',
  //     forbidClick: true,
  //   });
  //   timer = null;
  // }, 1000);
  return Promise.resolve(config);
})
axios.interceptors.response.use((res) => {
  Toast.clear();
  // clearTimeout(res.config.timer)
  // res.config.timer = null
  const { code, content } = res.data
  if (typeof res.data !== 'object') {
    Toast.fail('服务端异常！')
    return Promise.reject(res)
  }
  if (code != 200) {
    if (content) Toast.fail(content)
    if (code == 10400) {
      Dialog.confirm({
        title: '未登录',
        message: '是否前往登录',
      })
        .then(() => {
          window.location.href = openWebUrl + 'login?webUrl=' + window.location.href;
        })
        .catch(() => {
          // on cancel
        });

    }
    return Promise.reject(res.data)
  }

  return res.data
})

export default axios
